package com.dzt.androidframework.threadpool;

import android.os.Bundle;
import android.view.View;

import com.dzt.androidframework.R;
import com.dzt.androidframework.activity.TitleFrameActivity;
import com.dzt.androidframework.databinding.ActivityThreadPoolBinding;
import com.dzt.androidframework.utils.JLogKit;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolActivity extends TitleFrameActivity<ActivityThreadPoolBinding> {

	private final int CORE_POOL_SIZE = 1;//核心线程数
	private final int MAX_POOL_SIZE = 3;//最大线程数
	private final int BLOCK_SIZE = 2;//阻塞队列大小
	private final long KEEP_ALIVE_TIME = 2;//空闲线程超时时间
	private ThreadPoolExecutor executorPool;


	public class OnClickHandler {
		public void onCachedClick(View view) {
			ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
			for (int i = 0; i < 10; i++) {
				final int index = i;
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				cachedThreadPool.execute(new Runnable() {

					@Override
					public void run() {
						JLogKit.getInstance().i("index = " + index +
								" thread id = " + Thread.currentThread().getId());
					}
				});
			}
		}

		public void onFixedClick(View view) {
			ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
			for (int i = 0; i < 10; i++) {
				final int index = i;
				fixedThreadPool.execute(new Runnable() {

					@Override
					public void run() {
						try {
							JLogKit.getInstance().i("index = " + index +
									" thread id = " + Thread.currentThread().getId());
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
			}
		}

		public void onScheduledClick(View view) {
			ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
			scheduledThreadPool.schedule(new Runnable() {

				@Override
				public void run() {
					JLogKit.getInstance().i("delay 3 seconds" +
							" thread id = " + Thread.currentThread().getId());
				}
			}, 3, TimeUnit.SECONDS);

//			scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
//
//				@Override
//				public void run() {
//					JLogKit.getInstance().i("delay 1 seconds, and excute every 3 seconds");
//				}
//			}, 1, 3, TimeUnit.SECONDS);
		}

		public void onSingleClick(View view) {
			ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
			for (int i = 0; i < 10; i++) {
				final int index = i;
				singleThreadExecutor.execute(new Runnable() {

					@Override
					public void run() {
						try {
							JLogKit.getInstance().i("index = " + index +
									" thread id = " + Thread.currentThread().getId());
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
			}
		}

		public void onCustomClick(View view) {
			for (int num = 0; num < 6; num++) {//每个500ms添加一个任务到队列中
				try {
					JLogKit.getInstance().e("execute");// 监听相关数据
					executorPool.execute(new WorkerThread("thread-" + num));
				} catch (Exception e) {
					JLogKit.getInstance().e("threadtest", "AbortPolicy...");
				}
			}

			// 20s后，所有任务已经执行完毕，我们在监听一下相关数据
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(20 * 1000);
					} catch (Exception e) {

					}
					JLogKit.getInstance().i("monitor after");
				}
			}).start();
		}
	}

	// 模拟耗时任务
	public class WorkerThread implements Runnable {
		private String threadName;

		public WorkerThread(String threadName) {
			this.threadName = threadName;
		}

		@Override
		public synchronized void run() {

			int i = 0;
			boolean flag = true;
			try {
				while (flag) {
					Thread.sleep(1000);
					i++;
					JLogKit.getInstance().e("threadtest", "WorkerThread " + threadName + "  " + i);
					if (i > 2) flag = false;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		public String getThreadName() {
			return threadName;
		}
	}

	@Override
	protected void initData(Bundle savedInstanceState) {
		//创建线程池
		// 创建一个核心线程数为3、最大线程数为8，缓存队列大小为5的线程池
		executorPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
				TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(BLOCK_SIZE),
				Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
		executorPool.allowCoreThreadTimeOut(true);
	}

	@Override
	protected String[] initPermissions() {
		return new String[0];
	}

	@Override
	protected int getLayoutId() {
		return R.layout.activity_thread_pool;
	}

	@Override
	protected void initWidgets() {
		setTitle(getString(R.string.menu_13));
		bindingView.setHandler(new OnClickHandler());
	}
}
